// 引入koa
const Koa = require('koa')
// 引入koa-router
const KoaRouter = require('koa-router')
// 实例化Koa
const app = new Koa()
// 实例化router
const router = new KoaRouter()



// const koaBody = require('koa-body')
const Body = require('koa-bodyparser')
// 使用所有的路由及相关的方法
app.use(router.routes())
.use(router.allowedMethods())
// .use(koaBody())
.use(Body())
// 店铺的激活城市列表
const activeCitiesData = require('./datas/active_cities.json')
router.get('/eleven/getActiveCities', async (ctx,next)=>{
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(),2000))
	ctx.status = 200
	ctx.body = {
		code: 200,
		data: activeCitiesData
	}
})

// 该城市所有的店铺分类信息列表
let categoryData = require('./datas/category.json')
router.get('/eleven/getCategoryData', async (ctx, next) => {
	// 生成的H5应用存在跨域问题，通过CORS设置跨域配置
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(),2000))
	ctx.body = {
		code: 200,
		categoryData
	}
});

// 根据给定的中文城市、地区名称来获取其大众点评首页链接 
let cityListData = require('./datas/cityList.json');
router.get('/eleven/getCityListData', async (ctx, next) => {
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(),2000))
	ctx.body = {
		code: 200,
		data: cityListData
	};
});
// 获取某个城市的 当前可见有效的辖区信息，包含子地区

// 预约订座的8个列表

let orderListData = require('./datas/ordernew.json');
router.get('/eleven/pc/poi/list', async (ctx, next) => {
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(),2000))
	ctx.body = {
		code: 200,
		data: orderListData
	};
});




// 商店详情信息
let shopDetailData = require('./datas/detail1.json');
router.get("/eleven/shop/:shopId", async (ctx, next) => {
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(),2000))
	// 获取路径上的数据
	const params = ctx.params;
// 进行数据库比
	if(shopDetailData.find((item)=>{
	  return item = params.shopId
	})) {
		const detail = shopDetailData.find((item)=>item = params.shopId)
		   ctx.body = {
			   code: 200,
			   data: detail,
			   params
	   } 
	}

});
// 获取美食列表数据
// 需要数据query传参
let typeListData = require('./datas/foods.json');
router.post('/eleven/search', async (ctx, next) => {
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(),2000))
	const query = ctx.request.query

	if(typeListData.find((item)=>{
	  return item = query.keyword
	})) {
		
		ctx.body = {
			code: 200,
			data: typeListData,
			query
		};
	}

});
// 验证码
	const about = ctx =>{
			let str = '1234567890abcdefghijklmnopqrstuvwxyz'
			let randomNum = function(min,max){
			return Math.floor(Math.random()*(max-min)+min)
		}
	let numText =""
	for(let i=0;i<4;i++){
	let txt = str[randomNum(0,str.length)]
	numText+=txt
	}
// 导入响应体里
	ctx.response.body = {"success":"ok",data:numText};
	}
router.get('/eleven/about',about)


   const userList =  [{  
            username: 'admin',
            password: '123456',
            roles: 'admin',
            name: '张三',
            age: 23,
            job: '前端工程师',
            token: '000111222333444555666',
            id: '100',
        }, {
            username: 'editor',
            password: '123456',
            roles: 'editor',
            name: '测试1',
            age: 23,
            job: '前端工程师',
            token: '145145145123123123111',
            id: '101',
        }, {
            username: '@word(3, 5)',
            password: '123456',
            roles: 'editor',
            name: '@cname',
            'age|20-30': 21,
            'job|1': ['前端工程师', '后端工程师', 'UI工程师', '需求工程师'],
            token: '@guid()',
            id: '102',
    },]
// **************注册***************
router.post('/eleven/register', async (ctx, next) => {
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(), 2000))

	const query = ctx.request.query
	const { username, password } = query;
	let newArr = []
	const userLen = userList.filter(userList => userList.username == username).length
	if (userLen > 0) {
		ctx.response.body = {
			"success": "ok", data: {
				code: 1,
				msg: '用户名已存在'
			}
		};
	} else {
		ctx.response.body = {
			"success": "ok", data: {
				code: 200,
				msg: '注册成功'
			}
		};

		newArr = [{ username, password }]
		userList.push(...newArr)
		console.log(userList)
	}

});



// ************登录*********
router.post('/eleven/login', async (ctx, next) => {
	ctx.set('Access-Control-Allow-Origin', '*')
	const query = ctx.request.query
	const { username, password } = query; //将传递进来的数据保存

	for (let i = 0; i < userList.length; i++) {
		//判断userList中是否存在该用户并且用户密码是否正确
		if (username === userList[i].username && password === userList[i].password) {
			ctx.response.body = {
				"success":"ok",
				code: 200,
				data: {
					// username: userList[i].username,
					// roles: userList[i].roles,
					token: userList[i].token
				}
			}
		}

	}
});


// 主页的美食
let foodsListData = require('./datas/home.json');
router.post('/eleven/search', async (ctx, next) => {
	ctx.set('Access-Control-Allow-Origin', '*')
	await new Promise(resolve => setTimeout(() => resolve(),2000))
		ctx.body = {
			code: 200,
			data: foodsListData
		};
});

// 提示信息
app.listen('3001',error=>{
	if(error){
		console.log('服务器启动失败,',error)
		return
	}
	console.log('服务器启动成功')
	console.log('服务器地址为:http://localhost:3001')
})

